<%--
  - Copyright 2011 Angel Sanadinov
  -
  - This file is part of VBox WMI.
  -
  - VBox WMI is free software: you can redistribute it and/or modify
  - it under the terms of the GNU General Public License as published by
  - the Free Software Foundation, either version 3 of the License, or
  - (at your option) any later version.
  -
  - VBox WMI is distributed in the hope that it will be useful,
  - but WITHOUT ANY WARRANTY; without even the implied warranty of
  - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  - GNU General Public License for more details.
  -
  - You should have received a copy of the GNU General Public License
  - along with VBox WMI.  If not, see <http://www.gnu.org/licenses/>.
  --%>

<%@page import="Utilities.Functions"%>
<%@page import="Managers.Utilities.RequestResponseWrapper"%>
<%@page import="Utilities.ApplicationException"%>
<%@page import="Managers.Utilities.ResponseMessagesContainer"%>
<%@page import="Beans.Requests.UserManagement.UserPasswordResetRequest"%>
<%@page import="Beans.Requests.UserManagement.UserRemoveRequest"%>
<%@page import="Beans.Requests.UserManagement.UserModifyRequest"%>
<%@page import="Beans.Requests.UserManagement.UserCreateRequest"%>
<%@page import="Beans.Requests.UserManagement.UserPermissionsRequest"%>
<%@page import="Utilities.Constants"%>
<%@page import="Utilities.Constants.SendingRequestResult"%>
<%@page import="Beans.Responses.UserManagementResponse"%>
<%@page import="Utilities.UIFunctions"%>
<%@page import="Utilities.ParameterNames"%>
<%@page import="Utilities.ParameterNames.Service"%>
<%@page import="Managers.Utilities.User"%>
<%@page import="Beans.Requests.UserManagement.UserManagementRequest"%>
<%
    //retrieves user data from the session
    User userSessionData = (User)session.getAttribute(ParameterNames.SESSION_USER_OBJECT);

    //retrieves the "permissions" paramter, which denotes that the action ID has to
    //do with a user's permissions
    String permissions = request.getParameter("permissions");

    //attempts to retrieve the action ID
    int action = 0;
    try
    {
        action = Integer.parseInt(request.getParameter("action"));
    }
    catch(NumberFormatException e){}

    UserManagementRequest userRequest = null;
    switch(action)
    {
        //create user/permissions
        case 1:
        {
            if(permissions != null) //permissions are to be added
            {
                int affectedUserId = Constants.INVALID_USER_ID;
                int affectedServerId = Constants.INVALID_SERVER_ID;

                try
                {
                    affectedUserId = Integer.parseInt(request.getParameter("id"));
                }
                catch(NumberFormatException e){}

                try
                {
                    affectedServerId = Integer.parseInt(request.getParameter("permissions.create.server"));
                }
                catch(NumberFormatException e){}

                userRequest = new UserPermissionsRequest(userSessionData.getUserData().getUserId(),
                                                         affectedUserId,
                                                         affectedServerId,
                                                         request.getParameter("permissions.create.machines"),
                                                         request.getParameter("permissions.create.media"),
                                                         request.getParameter("permissions.create.networks"),
                                                         false);
            }
            else //a new user is to be added
            {
                int accountLevel = 0;
                try
                {
                    accountLevel = Integer.parseInt(request.getParameter("user.create.level"));
                }catch(NumberFormatException e){}

                String newUserPassword = request.getParameter("user.create.password");

                if(newUserPassword.equals(request.getParameter("user.create.password.confirm")))
                {
                    userRequest = new UserCreateRequest(userSessionData.getUserData().getUserId(),
                                                        request.getParameter("user.create.name"),
                                                        newUserPassword,
                                                        accountLevel);
                }
                else
                    ;
            }
        } break;
    
        //modify user/permissions
        case 2:
        {
            if(permissions != null) //permissions are to be modified
            {
                int affectedUserId = Constants.INVALID_USER_ID;
                int affectedServerId = Constants.INVALID_SERVER_ID;

                try
                {
                    affectedUserId = Integer.parseInt(request.getParameter("id"));
                }
                catch(NumberFormatException e){}

                try
                {
                    affectedServerId = Integer.parseInt(request.getParameter("serverId"));
                }
                catch(NumberFormatException e){}

                userRequest = new UserPermissionsRequest(userSessionData.getUserData().getUserId(),
                                                         affectedUserId,
                                                         affectedServerId,
                                                         request.getParameter("permissions.modify.machines"),
                                                         request.getParameter("permissions.modify.media"),
                                                         request.getParameter("permissions.modify.networks"),
                                                         true);
            }
            else //an existing user is to be modified
            {
                int affectedUserId = Constants.INVALID_USER_ID;

                try
                {
                    affectedUserId = Integer.parseInt(request.getParameter("id"));
                }
                catch(NumberFormatException e){}

                userRequest = new UserModifyRequest(userSessionData.getUserData().getUserId(), affectedUserId);

                int accountLevel = 0;
                try
                {
                    accountLevel = Integer.parseInt(request.getParameter("user.modify.level"));
                }catch(NumberFormatException e){}

                ((UserModifyRequest)userRequest).setAccountLevel(accountLevel);
            }
        } break;

        //remove user/permissions
        case 3:
        {
            if(permissions != null) //permissions are to be removed
            {
                int affectedUserId = Constants.INVALID_USER_ID;
                int affectedServerId = Constants.INVALID_SERVER_ID;

                try
                {
                    affectedUserId = Integer.parseInt(request.getParameter("id"));
                }
                catch(NumberFormatException e){}

                try
                {
                    affectedServerId = Integer.parseInt(request.getParameter("serverId"));
                }
                catch(NumberFormatException e){}

                userRequest = new UserPermissionsRequest(userSessionData.getUserData().getUserId(),
                                                           affectedUserId,
                                                           affectedServerId);
            }
            else //an existing user is to be removed
            {
                int affectedUserId = Constants.INVALID_USER_ID;

                try
                {
                    affectedUserId = Integer.parseInt(request.getParameter("id"));
                }
                catch(NumberFormatException e){}

                userRequest = new UserRemoveRequest(userSessionData.getUserData().getUserId(), affectedUserId);
            }
        } break;
    
        //reset an existing user's password
        case 4:
        {
            int affectedUserId = Constants.INVALID_USER_ID;
            String newPassword = request.getParameter("reset.newPassword");

            //checks if the supplied passwords are identical
            if(newPassword.equals(request.getParameter("reset.newPassword.confirm")))
            {
                try
                {
                    affectedUserId = Integer.parseInt(request.getParameter("id"));
                }
                catch(NumberFormatException e){}

                if(affectedUserId == userSessionData.getUserData().getUserId())
                {
                    userRequest = new UserPasswordResetRequest(affectedUserId,
                                                               request.getParameter("reset.oldPassword"),
                                                               newPassword);
                }
                else
                {
                    userRequest = new UserPasswordResetRequest(userSessionData.getUserData().getUserId(),
                                                               affectedUserId,
                                                               newPassword);
                }
            }
        } break;

        default: ; break;
    }

    //attempts to send the request and retrieves the response
    SendingRequestResult sendingResult = UIFunctions.sendServiceRequest(request, response, userRequest, Service.USERS_MANAGEMENT);
    if(sendingResult != SendingRequestResult.OK)
    {
        //retrieves the user's messages container
        ResponseMessagesContainer messagesContainer =
            (ResponseMessagesContainer)request.getSession(false).getAttribute(ParameterNames.SESSION_REQUEST_MESSAGES_OBJECT);

        int exceptionCode = UIFunctions.parseSendingRequestResult(sendingResult);

        //adds the response from the failed operation
        UserManagementResponse userResponse = new UserManagementResponse(false, new ApplicationException(exceptionCode));
        messagesContainer.put(new RequestResponseWrapper(userRequest, userResponse));
    }
    else
        ;

    //selects the proper redirect page
    int userId = Constants.INVALID_USER_ID;
    try
    {
        userId = Integer.parseInt(request.getParameter("id"));
    }
    catch(NumberFormatException e){}

    if(Functions.isUserIdValid(userId) && action != 3)
        response.sendRedirect("users.jsp?id=" + userId);
    else
        response.sendRedirect("users.jsp");
%>